import {getUserInfo} from "../../../api/userInfo"
import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let ret = await getUserInfo()
    this.setData({
      imageUrl:ret.imageUrl,
      phoneNumber:ret.phoneNumber
    })
  },

  // 保存图片
  download(){
    wx.downloadFile({
      url: this.data.imageUrl,
      success(res){
        wx.saveImageToPhotosAlbum({
          filePath:res.tempFilePath,
          success(res){   
            Toast({
              message:"图片已保存至系统相册"
            })
          },
          fail(err){
            console.log("inner",err)
            Toast({
              message:"保存失败"
            })
          }
        })
      },
      fail(err){
        console.log(err);
      }
    })
  },

  // 替换图片
  change(){
    wx.chooseMedia({
      count:1,
      sourceType:['album', 'camera'],
      mediaType:["image"],
      sizeType:["compressed"]
    }).then(res=>{
      let {tempFiles} = res
      this.setData({
        tempFilePath:tempFiles[0].tempFilePath
      })
      let {phoneNumber} = this.data
      // console.log(tempFiles[0].tempFilePath)
      let that = this
      wx.uploadFile({
        filePath: tempFiles[0].tempFilePath,
        name: "imageInfo",
        url: "http://127.0.0.1:3000/upload/image",
        formData:{
          phoneNumber,
        },
        success(res){
          console.log(res)
          let ret = JSON.parse(res.data)
          if(ret.code === 200){
            Toast({
              type:"success",
              message:"修改成功"
            })
            that.setData({
              imageUrl:tempFiles[0].tempFilePath
            })
          }
        },
        fail(err){
          console.log(err);
          Toast({
            type:"fail",
            message:"修改失败"
          })
        }
      })
    }).catch(err=>{
      console.log(err)
    })
  }
})